from utils.common_import import *

from .model import Node_Attribute, Resource_Action_Log, ResourceLogQuerySchema, \
    ResourceAddSchema, ResourceDeleteSchema
from .node_new import get_nodes_resource_by_cluster_name
from utils.ext import inner_db, db_query_record, db_add_record, db_update_record, db_delete_record, db_transaction

class UnavailableResource(Resource):
    # @jwt_required()
    @exception_response()
    def get(self):
        records = db_query_record(Node_Attribute)

        return make_success_response(records)

    # @jwt_required()
    @permission_auth("admin")
    @request_arg_check(ResourceAddSchema(), many=False)
    @exception_response()
    @db_transaction(inner_db.session)
    def post(self):
        request_data = current_schema_instance

        db_add_record(session=inner_db.session,
                      table_schema=Node_Attribute,
                      filter_info=dict(node_id = request_data['node_id']),
                      add_info=dict(node_id= request_data['node_id'],
                                            unhealthy_gpu = request_data['unhealthy_gpu']))

        db_add_record(session=inner_db.session,
              table_schema=Resource_Action_Log,
              filter_info={},
              add_info= dict(node_id = request_data['node_id'],
                             value_before = 0,
                             value_after = request_data['unhealthy_gpu'],
                             action = "add",
                             remark = request_data['remark'],
                             operator = current_identity.email)
                      )

        return make_no_data_response(status=200, code=0, message="success")

    # @jwt_required()
    @permission_auth("admin")
    @request_arg_check(ResourceAddSchema(), many=False)
    @exception_response()
    @db_transaction(inner_db.session)
    def put(self):
        request_data = current_schema_instance

        result = Node_Attribute.query.\
                    filter_by(node_id = request_data['node_id']).first()

        logger.info(result)
        #记录已经存在，创建失败
        if not result:
            return make_error_response(status=403, code=403,
                            message="record does not exist node_id:{}, please check".format(request_data['node_id']))

        value_before = result.unhealthy_gpu

        db_update_record(session=inner_db.session,
                       table_schema=Node_Attribute,
                       filter_info=dict(node_id = request_data['node_id']),
                       update_info=dict(node_id= request_data['node_id'],
                                            unhealthy_gpu = request_data['unhealthy_gpu']))

        db_add_record(session=inner_db.session,
              table_schema=Resource_Action_Log,
              filter_info={},
              add_info= dict(node_id = request_data['node_id'],
                             value_before = value_before,
                             value_after = request_data['unhealthy_gpu'],
                             action = "update",
                             remark = request_data['remark'],
                             operator = current_identity.email)
                      )

        return make_no_data_response(status=200, code=0, message="success")

    # @jwt_required()
    @permission_auth("admin")
    @request_arg_check(ResourceDeleteSchema(), many=False)
    @exception_response()
    @db_transaction(inner_db.session)
    def delete(self):
        request_data = current_schema_instance

        result = Node_Attribute.query.\
                    filter_by(node_id = request_data['node_id']).first()

        logger.info(result)
        #记录已经存在，创建失败
        if not result:
            return make_error_response(status=403, code=403,
                            message="record does not exist node_id:{}, please check".format(request_data['node_id']))

        value_before = result.unhealthy_gpu
        db_delete_record(session=inner_db.session,
                         table_schema=Node_Attribute,
                         filter_info=dict(node_id = request_data['node_id']))

        db_add_record(session=inner_db.session,
              table_schema=Resource_Action_Log,
              filter_info={},
              add_info= dict(node_id = request_data['node_id'],
                             value_before = value_before,
                             value_after = 0,
                             action = "delete",
                             remark = "delete",
                             operator = current_identity.email)
                      )

        return make_no_data_response(status=200, code=0, message="success")

class UnavailableResourceLog(Resource):
    # @jwt_required()
    @exception_response()
    def get(self):
        records = db_query_record(Resource_Action_Log)

        return make_success_response(records)

class UnavailableResourceLogSearch(Resource):
    # @jwt_required()
    @request_arg_check(ResourceLogQuerySchema(), many=False, location="args")
    @exception_response()
    def get(self):
        node_id = current_schema_instance['node_id']
        print(node_id)
        records = []
        results = Resource_Action_Log.query \
                    .filter_by(node_id = node_id)\
                    .order_by(inner_db.desc(Resource_Action_Log.action_time))

        for record in results:
            records.append(record.get_data_info())

        return make_success_response(records)


class NodeResources(Resource):
    # @jwt_required()
    @exception_response()
    def get(self):
        nodes_resources = get_nodes_resource_by_cluster_name()
        return make_success_response(nodes_resources)
